package com.esiran.payadmin.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.esiran.payadmin.exception.APIRespException;
import com.esiran.payadmin.model.Order;
import com.esiran.payadmin.service.AliPayService;
import com.esiran.payadmin.util.IOUtilEx;
import com.esiran.payadmin.util.MapUtilEx;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import sun.misc.IOUtils;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {
    @Override
    public  String createQRCodeByOrder(Order order,String notifyUrl) throws APIRespException {
        if(order == null){
            return null;
        }
        Map<String,Object> payload = new HashMap<>();
        payload.put("subject",order.getGoodsName());
        payload.put("out_trade_no",order.getNum());
        payload.put("total_amount",order.getMoney());
        return requestQRCode(payload,notifyUrl);
    }
    public static String requestQRCode(Map<String,Object> payload,String notifyUrl) throws APIRespException {
        if (payload == null){
            return null;
        }
        String[] alipayKeys = getKeys();
        if (alipayKeys == null){
            throw new APIRespException("创建支付宝订单失败",-1002);
        }
        AlipayClient alipayClient = new DefaultAlipayClient(
                ALIPAY_GATEWAY, ALIPAY_APP_ID,alipayKeys[0],
                "json","UTF-8",alipayKeys[1],
                "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(notifyUrl);
        request.setBizContent(MapUtilEx.toJson(payload));
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return response.getQrCode();
            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            return null;
        }
    }
    public static String[] getKeys(){
        try{
            return new String[]{
                    IOUtilEx.readTextFile(ALIPAY_KEY_PRIVATE),
                    IOUtilEx.readTextFile(ALIPAY_KEY_GLOBAL_PUBLIC),
            };
        }catch (IOException e){
            return null;
        }
    }
}
